<template>
  <div class="chat-room-user">
    <div
      class="server-btn juzhong"
      title="客服咨询"
      @click="show = true"
      :style="{ bottom, right, width, height, background, borderRadius }"
    >
      <i class="el-icon-headset"></i>
    </div>
    <div v-if="show" :class="`chat-wrap chat-theme-${theme}`">
      <i title="关闭" class="el-icon-close" @click="show = false"></i>
      <div class="chat-head">
        <img class="chat-logo" src="../../assets/images/chat-logo.svg" alt="" />
      </div>
      <div class="chat-main">
        <div ref="chatDom" class="chat-left chat-list chat-scrollbar">
          <div class="chat-server-wrap juzhong">
            <span class="chat-server">
              <span class="svc-name"
                >{{ serverType[userType].name }}&nbsp;正在为您服务</span
              >
            </span>
            <i
              class="el-icon-headset"
              :class="{ 'server-active': userType === 'server' }"
              title="转人工客服"
              @click="handleToServer"
            ></i>
          </div>
          <template v-for="(item, i) in chatList">
            <div v-if="item.type === 0" :key="i" class="chat-item chat-item-0">
              <img class="svc-avatar" :src="item.avatar" alt="" />
              <div>
                <p class="service-nickname">{{ item.name }}&nbsp;&nbsp;{{ item.time }}</p>
                <p class="say-con" v-html="item.msg"></p>
              </div>
            </div>
            <div v-if="item.type === 1" :key="i" class="chat-item chat-item-1">
              <p class="service-nickname">您&nbsp;&nbsp;{{ item.time }}</p>
              <p class="say-con" v-html="item.msg"></p>
            </div>
          </template>
          <div class="chat-server-wrap juzhong" v-if="seeyou">
            <span class="chat-server">感谢您的咨询，再见！</span>
          </div>
        </div>
        <div class="chat-right">
          <div class="server-tab juzhong">客服信息</div>
          <div class="server-info juzhong">
            <img class="server-avatar" :src="serverType[userType].avatar" alt="" />
            <p>客服：{{ serverType[userType].name }}</p>
            <p>部门：{{ serverType[userType].dept }}</p>
          </div>
        </div>
      </div>
      <div class="chat-foot">
        <div class="chat-left">
          <div
            ref="chatIpt"
            class="chat-input chat-scrollbar"
            contenteditable
            placeholder=" 请输入你要咨询的问题..."
          ></div>
          <div class="chat-input-send">
            <i
              class="el-icon-phone"
              :class="{ 'server-active': dialogVisible }"
              title="音视频通话"
              @click="handleToWebRTC"
            ></i>
            <span class="chat-send-btn juzhong" @click="handleSend">发送</span>
          </div>
        </div>
        <div class="chat-right chat-banner">
          <el-carousel height="150px">
            <el-carousel-item v-for="(item, i) in imgTabs" :key="i">
              <div class="swiper-slide" @click="handleImgTo(item)">
                <span class="banner-name">{{ item.name }}</span>
                <img class="swiper-img" :src="item.img" alt="" />
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
    </div>
    <el-dialog title="音视频通话" :visible.sync="dialogVisible" width="700px" :before-close="handleCloseRTC">
      <video id="localVideo" ref="localVideo" autoplay playsinline></video>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCloseRTC">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "UserChatSystem",
  props: {
    theme: {
      type: String,
      default: "orange",
    },
    bottom: {
      type: String,
      default: "40px",
    },
    right: {
      type: String,
      default: "10px",
    },
    width: {
      type: String,
      default: "46px",
    },
    height: {
      type: String,
      default: "46px",
    },
    borderRadius: {
      type: String,
      default: "46px",
    },
    background: {
      type: String,
      default: "#fff",
    },
  },
  data() {
    return {
      dialogVisible: false,
      localStream: null,
      show: false,
      seeyou: false,
      userType: "robot",
      serverType: {
        server: {
          name: "大箴 - 陈安然",
          dept: "行政部门",
          avatar: "http://10.50.101.20:90/imgs/server-avatar.png",
        },
        robot: {
          name: "大箴智能客服",
          dept: "智能AI",
          avatar: "http://10.50.101.20:90/imgs/ai-avatar.png",
        },
      },
      ws: null,
      imgTabs: [
        {
          img: require("../../assets/images/about-banner.svg"),
          link: "https://www.adayun.com/#/about",
          name: "关于我们",
        },
        {
          img: require("../../assets/images/honor-banner.png"),
          link: "https://www.adayun.com/#/honor",
          name: "荣誉资质",
        },
        {
          img: require("../../assets/images/joins.png"),
          link: "https://www.adayun.com/#/joinUs",
          name: "加入我们",
        },
      ],
      chatList: [],
      userId: Math.random().toFixed(6).slice(2),
    };
  },
  mounted() {
    this.initWebSocket();
    this.enterKeyup();
  },
  destroyed() {
    this.enterKeyupDestroyed();
    this.ws.close();
  },
  methods: {
    handleCloseRTC() {
      const tracks = this.$refs.localVideo.srcObject.getTracks();
      for (let i = 0; i < tracks.length; i++) {
        tracks[i].stop();
      }
      this.dialogVisible = false;
    },
    handleToWebRTC() {
      this.dialogVisible = true;
      // 设置约束
      const mediaStreamConstraints = {
        video: true,
      };
      // getUserMedia 获得流后，将音视频流展示并保存到 localStream
      const gotLocalMediaStream = (mediaStream) => {
        this.$refs.localVideo.srcObject = mediaStream;
        this.localStream = mediaStream;
      };
      navigator.mediaDevices
        .getUserMedia(mediaStreamConstraints)
        .then(gotLocalMediaStream)
        .catch((err) => {
          console.log("getUserMedia 错误", err);
        });
    },
    handleToServer() {
      this.seeyou = false;
      this.userType = "server";
      const params = JSON.stringify({
        userType: this.userType,
        isUser: true,
        userId: this.userId,
        initServer: true,
        msg: "转人工服务",
      });
      this.ws.send(params);
    },
    initWebSocket() {
      //判断页面有没有存在websocket连接
      if (window.WebSocket) {
        // 8181 端口号 要与后端配置的一致
        const url = "ws://127.0.0.1:8181?userId=" + this.userId;
        const ws = new WebSocket(url);
        ws.onopen = (e) => {
          console.log("服务器连接成功");
        };
        ws.onclose = (e) => {
          console.log("服务器连接关闭");
        };
        ws.onerror = () => {
          console.log("服务器连接出错");
        };
        ws.onmessage = (e) => {
          //接收服务器返回的数据
          const res = JSON.parse(e.data);
          if (res.closeServer) {
            this.seeyou = true;
            this.userType = "robot";
          }
          this.chatList.push(res);
          this.scrollToBottom();
        };
        this.ws = ws;
      } else {
        console.log("浏览器不支持websocket");
      }
    },
    enterKey(e) {
      const code = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
      if (!e.shiftKey && code === 13) {
        this.handleSend();
        e.preventDefault();
        return false;
      }
    },
    enterKeyupDestroyed() {
      document.removeEventListener("keydown", this.enterKey);
    },
    enterKeyup() {
      document.addEventListener("keydown", this.enterKey);
    },
    scrollToBottom() {
      const el = this.$refs.chatDom;
      this.$nextTick(() => {
        if (el) {
          el.scrollTop = el.scrollHeight;
        }
      });
    },
    handleSend() {
      const el = this.$refs.chatIpt;
      const msg = el.innerHTML;
      if (!msg) {
        return;
      }
      const params = {
        userType: this.userType,
        isUser: true,
        msg,
        userId: this.userId,
      };
      this.ws.send(JSON.stringify(params));
      el.innerHTML = "";
      this.seeyou = false;
    },
    handleImgTo(item) {
      window.open(item.link);
    },
  },
};
</script>
<style lang="less">
@import "../../assets/style/scrollbar.less";
.chat-room-user {
  display: flex;
  align-items: center;
  justify-content: center;
  video {
    width: 100%;
    border-radius: 4px;
  }
  // navy 天蓝色
  .chat-theme-navy {
    .chat-head,
    .chat-item-1 .say-con,
    .chat-send-btn {
      background: #409eff !important;
    }
    .server-active {
      color: #409eff !important;
    }
  }
  // 橘黄色
  .chat-theme-orange {
    .chat-head,
    .chat-item-1 .say-con,
    .chat-send-btn {
      background: #fd9355 !important;
    }
    .server-active {
      color: #fd9355 !important;
    }
  }
  // 暗黑色
  .chat-theme-dark {
    .chat-head,
    .chat-item-1 .say-con,
    .chat-send-btn {
      background: #303133 !important;
    }
    .server-active {
      color: #303133 !important;
    }
  }
  .server-btn {
    cursor: pointer;
    z-index: 9999;
    position: fixed;
    bottom: 40px;
    right: 10px;
    width: 46px;
    height: 46px;
    border-radius: 46px;
    background: #fff;
    box-shadow: 0 0 8px rgb(#000, 14%);
    margin: 0 auto 6px;
    transition: all 0.3s;
    .el-icon-headset {
      font-size: 20px;
    }
  }
  .el-carousel__indicators {
    white-space: nowrap;
  }
  .el-carousel__container {
    height: 100%;
  }
  .el-carousel {
    width: 100%;
  }
  .banner-name {
    z-index: 1;
    color: #fff;
    font-size: 24px;
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    font-family: monospace;
  }
  .server-active {
    color: #409eff;
  }
  img {
    object-fit: contain;
  }
  .chat-item-1 {
    padding-left: 40px;
    text-align: right;
    .service-nickname {
      margin-bottom: 8px;
    }
    .say-con {
      text-align: justify;
      display: inline-block;
      word-wrap: break-word;
      background-color: #409eff;
      border-radius: 16px 0 16px 16px;
      box-shadow: 0 0 5px rgb(#000, 6%);
      line-height: 20px;
      margin: 0;
      min-height: 20px;
      padding: 8px 13px;
      word-break: break-all;
      color: #fff;
    }
  }
  .chat-item-0 {
    padding-right: 40px;
    display: flex;
    .svc-avatar {
      width: 36px;
      height: 36px;
      margin-right: 12px;
    }
    .service-nickname {
      margin-bottom: 8px;
    }
    .say-con {
      text-align: justify;
      display: inline-block;
      word-wrap: break-word;
      background: #f2f2fb;
      border: 1px solid #f2f2fb;
      border-radius: 0 16px 16px 16px;
      box-shadow: 0 1px 6px 0 #cfd1d3;
      line-height: 20px;
      margin: 0;
      min-height: 20px;
      padding: 8px 13px;
      word-break: break-all;
    }
  }
  .chat-item {
    margin-bottom: 20px;
  }
  .chat-server-wrap {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    position: sticky;
    width: 100%;
    top: 0;
    .el-icon-headset {
      position: absolute;
      right: 0;
      cursor: pointer;
      font-size: 18px;
    }
  }
  .chat-server {
    padding: 5px 20px;
    background: #f2f2fb;
    border-radius: 15px;
    color: #919bb0;
    white-space: nowrap;
  }
  .chat-list {
    position: relative;
    padding: 8px;
  }
  .chat-input {
    padding: 8px;
    outline: none;
    height: 110px;
    line-height: 20px;
  }
  .chat-input-send {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 8px;
    .el-icon-phone {
      font-size: 20px;
      cursor: pointer;
    }
  }
  .chat-send-btn {
    background: #409eff;
    cursor: pointer;
    width: 60px;
    height: 28px;
    color: #fff;
    border-radius: 3px;
  }
  .chat-input:empty:before {
    color: #919bb0;
    content: attr(placeholder);
  }
  .swiper-slide {
    overflow: hidden;
    height: 150px;
    cursor: pointer;
  }
  .swiper-img {
    width: 100%;
    border: none;
  }
  .juzhong {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .server-tab {
    height: 40px;
    border-bottom: 1px solid #e0e4ea;
  }
  .server-info {
    height: 340px;
    flex-direction: column;
    p {
      width: 120px;
      white-space: nowrap;
      text-align: left;
      margin-bottom: 4px;
    }
    .server-avatar {
      width: 120px;
      margin-bottom: 8px;
    }
  }
  .chat-wrap {
    overflow: hidden;
    width: 800px;
    height: 600px;
    background: #fff;
    border-radius: 14px;
    font-size: 12px;
    box-shadow: 0 2px 20px 8px rgb(#000, 0.2);
    position: relative;
    .el-icon-close {
      cursor: pointer;
      position: absolute;
      right: 10px;
      top: 10px;
      color: #fff;
      font-size: 20px;
    }
  }
  .chat-head {
    display: flex;
    align-items: center;
    height: 70px;
    background: #409eff;
    .chat-logo {
      width: 150px;
      margin-left: 20px;
    }
  }
  .chat-main {
    height: 380px;
    display: flex;
  }
  .chat-foot {
    height: 150px;
    display: flex;
    border-top: 1px solid #e0e4ea;
  }
  .chat-left {
    flex: 1;
    border-right: 1px solid #e0e4ea;
  }
  .chat-right {
    width: 210px;
  }
  .chat-banner {
    overflow: hidden;
    position: relative;
  }
  .swiper-pagination-bullets {
    position: absolute;
    text-align: center;
    z-index: 1;
  }
}
</style>
